package com.palmelf.ipms.tools;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.extend.HandlerMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myapps.bean.User;
import com.myapps.controllers.ServiceHandler;


/**
 * 开发调试使用的 Jetty Server
 * 
 * @author badqiu
 * 
 */
public class JettyServer {
    protected final static Log logger = LogFactory.getLog(JettyServer.class);


    public static void main(String[] args) throws Exception {
        Server server = buildNormalServer(8082, "/hw");
        server.start();
        WebAppContext context = (WebAppContext) server.getHandler();
        WebApplicationContext wac =
                WebApplicationContextUtils.getRequiredWebApplicationContext(context.getServletContext());
        // 打印映射信息
        Map<Integer, HandlerMethod> m = wac.getBean(ServiceHandler.class).getHandlerMethods();
        System.out.println(m.toString());
        Iterator<Entry<Integer, HandlerMethod>> iter = m.entrySet().iterator();
        while (iter.hasNext()) {
            HandlerMethod method = iter.next().getValue();
            Object obj = wac.getBean((String) method.getBean());
            System.out.println(obj);
            // method.getMethod().invoke(obj, "xxxxxxxxxxxxxx");
        }
        System.out.println("==============================");
        HandlerMethod hm = m.get(1);
        // hm.getMethod().invoke(wac.getBean((String) hm.getBean()), "xxxxx");
        Method method = hm.getMethod();
        Class<?>[] paramters = method.getParameterTypes();
        User u = new User();
        u.setName("xxxxxxxxxxxxxxxxxxxxxxxx");
        u.setAge(1);
        String json = JSON.toJSONString(u);
        // 此处演示动态反序列化对象和调用实现方法
        for (Class<?> class1 : paramters) {
            Object param = JSON.parseObject(json.getBytes(), class1);
            System.out.println(class1);
            System.out.println(param);
            hm.getMethod().invoke(wac.getBean((String) hm.getBean()), param);
        }
    }


    /**
     * 创建用于正常运行调试的Jetty Server, 以src/main/webapp为Web应用目录.
     */
    public static Server buildNormalServer(int port, String contextPath) {
        Server server = new Server(port);
        WebAppContext webContext = new WebAppContext("src/main/webapp", contextPath);
        webContext.setClassLoader(Thread.currentThread().getContextClassLoader());
        server.setHandler(webContext);
        server.setStopAtShutdown(true);

        return server;
    }

}
